package com.xmc.servlet;

import com.xmc.dao.UserDao;
import com.xmc.pojo.User;
import com.xmc.utils.BaseContext;
import com.xmc.utils.Result;
import com.xmc.utils.ResultWriter;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.UUID;

/**
 * @author 谢孟呈
 */
@WebServlet(urlPatterns = "/file/upload")//分的子路由
public class PicServlet extends HttpServlet {

	//接图片
    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response) {
        User user = BaseContext.getCurrentUser(request);
        UserDao userDao = new UserDao();
    //转编码格式
        try {
            request.setCharacterEncoding("utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        FileItemFactory f =new DiskFileItemFactory();
        ServletFileUpload su =new ServletFileUpload(f);
        try{
            List<FileItem> items =su.parseRequest(request);
            if(items.size()>0){
                FileItem item =items.get(0);
                if(!item.isFormField()){
                    //文件名字
                    String name =item.getName();
                    //文件后缀
                    String fExt =name.substring(name.lastIndexOf("."));
                    //为了避免重复 改名
                    String newName = UUID.randomUUID().toString().replaceAll("-","")+fExt;
                    String path = "D:/javaProject/mavenProject/MyStudentMaster/src/main/webapp/static/images/user/"+newName;
                    //把图片保存路径放到数据库以备下次使用
                    item.write(new File(path));
                    boolean isSuccess = userDao.updateImg(user.getCode(), newName);
                    if (isSuccess) {
                        Result res = new Result(true, "存储图片成功");
                        ResultWriter.write(response,res);
                    }
                }
            }
        } catch (FileUploadException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);

    }
}

